#include "server_log.h"

#define LOG_OUTPUT_BUFFER_SIZE 1024

char buffer[LOG_OUTPUT_BUFFER_SIZE];

static LogOutputType    log_output_type = LOG_OUTPUT_TYPE_CONSOLE;
static FILE *           log_file        = NULL;

void server_log_init(LogOutputType type) {
    switch (type)
    {
    case LOG_OUTPUT_TYPE_CONSOLE:
        log_output_type = LOG_OUTPUT_TYPE_CONSOLE;
        break;
    case LOG_OUTPUT_TYPE_FILE:
        log_output_type = LOG_OUTPUT_TYPE_FILE;
        log_file = fopen(LOG_FILE_PATH, "a");
        if (log_file == NULL) {
            log_output_type = LOG_OUTPUT_TYPE_CONSOLE;
            server_log(LOG_SYSTEM, "Failed to open log file! The log will be printed to the console!\n"); // 打开失败，输出到控制台
        }
        break;
    default:
        break;
    }
    
}
void _server_log(LogClass log_class, const char* format, ...) {
    char* buffer_pointer = buffer;
    *buffer_pointer = '\0';

    // 获取系统时间  
    time_t current_time_s;
    time(&current_time_s);
    struct tm* current_time = localtime(&current_time_s);

    sprintf(buffer_pointer, "%04d-%02d-%02d %02d:%02d:%02d ",
        current_time->tm_year + 1900,
        current_time->tm_mon + 1,
        current_time->tm_mday,
        current_time->tm_hour,
        current_time->tm_min,
        current_time->tm_sec
    );

   while (*buffer_pointer != '\0') {
       buffer_pointer++;
   }
   
   va_list args;  
   va_start(args, format);  
   switch(log_class) {  
       case LOG_SYSTEM:  
           sprintf(buffer_pointer,"[SYSTEM] ");
           break;  
       case LOG_INFO:  
           sprintf(buffer_pointer,"[INFO]   ");
           break;  
       default:  
           sprintf(buffer_pointer,"[UNKNOWN]");
           break;  
   }  

   while(*buffer_pointer != '\0') {  
       buffer_pointer++;  
   }  

   vsprintf(buffer_pointer,format, args);  
   va_end(args);  

   switch(log_output_type) {  
       case LOG_OUTPUT_TYPE_CONSOLE:  
           printf("%s\n", buffer);  
           break;  
       case LOG_OUTPUT_TYPE_FILE:  
           if (log_file != NULL) {  
               fprintf(log_file, "%s\n", buffer);  
           }else{  
               log_output_type = LOG_OUTPUT_TYPE_CONSOLE;  
               server_log(LOG_SYSTEM, "Failed to write log file! The log will be printed to the console!\n"); // 打开失败，输出到控制台  
           }  
           break;  
       default:  
           break;  
   }  
}
